package com.rf.richfitwheel.admin.conf;

import feign.RequestInterceptor;
import feign.RequestTemplate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Configuration
@Component
@EnableFeignClients(basePackages = "com.**.feignclient")
public class FeignClientsConfigurationCustom implements RequestInterceptor {

	@Autowired
	private CommonPropertiesConfig commonPropertiesConfig;
	
	@Override
	public void apply(RequestTemplate template) {
		//服务间认证用的token
		template.header("feignAccessToken", commonPropertiesConfig.getFeignAccessToken());

		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();  
	    if (requestAttributes == null) {  
	      return;  
	    }  

		HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
		Enumeration<String> headerNames = request.getHeaderNames();
		if (headerNames != null) {
			while (headerNames.hasMoreElements()) {
				String name = headerNames.nextElement();
				//content-type被修改后，容易报415的错误，建议使用默认值
				if(!"content-type".equals(name)){
				Enumeration<String> values = request.getHeaders(name);
				while (values.hasMoreElements()) {
					String value = values.nextElement();
					template.header(name, value);
				}
			}
		}
	}
	}

	@Bean
	public FeignHystrixConcurrencyStrategy feignHystrixConcurrencyStrategy() {
		return new FeignHystrixConcurrencyStrategy();
	}

}
